import store from '@/store/index.js';
import config from '../config.js';
import handle from '@/common/messageHandler.js'
import {pub, sub} from '@/common/event.js'
let socketOpen = false;
let socketMsgQueue = [];
let st;
let stping;
let init_id;
let start = false

sub("logout",function(){
	start = false
	uni.closeSocket({
		success() {
			console.log("消息中心-sub关闭")
		}
	})
})

const init = (id) => {
	start = true
	init_id = id
	uni.connectSocket({
		url: config.webSocketUrl + "/" + id,
	});
	uni.onSocketOpen(function(res) {
		console.log(`websocket 已连接`,res)
		// 同步数据
		pub("relink",{})
		socketOpen = true;
		store.commit(`websocket/setConnectState`,true)
		clearInterval(st)
		st = null
		stping = setInterval(()=>{
			sendSocketMessage({
				type:"ping",
				data:{}
			})
		},10000)
		for (var i = 0; i < socketMsgQueue.length; i++) {
			sendSocketMessage(socketMsgQueue[i]);
		}
		socketMsgQueue = [];
	});
	
	uni.onSocketError(function(res) {
		console.log('WebSocket 出错！');
		uni.closeSocket()
		socketOpen = false
		store.commit(`websocket/setConnectState`,false)
		if(stping){
			clearInterval(stping)
			stping = null
		}
		if(st) return
		// 尝试重连
		st = setInterval(() => {
			if(!store.state.user.user || !store.state.user.user.id){
				return
			}
			console.log('WebSocket 尝试链接或重连！');
			if(socketOpen){
				clearInterval(st)
				st = null
				return
			}
			if(start){
				init(init_id)
			}
		}, 5000)
	});
	
	uni.onSocketClose(function(res) {
		console.log('WebSocket 已关闭！');
		socketOpen = false
		store.commit(`websocket/setConnectState`,false)
		if(st) return
		// 尝试重连
		st = setInterval(() => {
			if(!store.state.user.user || !store.state.user.user.id){
				return
			}
			console.log('WebSocket 尝试链接或重连！');
			if(socketOpen){
				clearInterval(st)
				st = null
				return
			}
			if(start){
				init(init_id)
			}
		}, 5000)
	});
}

uni.onSocketMessage(function(res) {
	// console.log('收到服务器内容：', res);
	const message = res.data
	handle.handle(JSON.parse(message))
});

function sendSocketMessage(msg) {
	console.log("Send:::",msg)
	if(store.state.user.user.id){
		msg.user = {
			id:store.state.user.user.id,
			name:store.state.user.user.name
		}
	}
	if (socketOpen) {
		uni.sendSocketMessage({
			data: JSON.stringify(msg)
		});
	} else {
		if(msg.type != "ping"){
			socketMsgQueue.push(msg);
		}
	}
}

module.exports = {
	send: sendSocketMessage,
	init:init
}